import path from 'path';
import fsExtra from 'fs-extra';
import moment from 'moment';
import appRoot from 'app-root-path';
import fs from 'fs';
import log from '../../../log';
import * as utils from '../../../util';
import config from '../../../../etc';
import * as proCore from '../product/core';
import db from '../../xp/db';
//import * as proImgCore from '../productimages/core';

export function upload(ctx) {
    return utils.resolve().then(() => {
        const {files: {file}, fields: {productId} = {}} = ctx.request.body;
        if (!file || !file.size) {
            throw '文件为空!';
        }
        const filepath = file.path;
        const nowStr = moment().format('YYYYMMDDHHmmss');
        const newFilenName = `${nowStr}${utils.randomDigits(4)}_${String(productId !== 'undefined' ? productId : '')}_${file.name}`;
        const url = path.join(config.productImgDir, moment().format('YYYYMMDD'), newFilenName);
        const destFilePath = path.join(appRoot.toString(), url);
        log.info('rename 图片 %s--->%s', filepath, destFilePath);
        return new Promise((resolve, reject) => {
            fsExtra.move(filepath, destFilePath, (err) => {
                if (err) {
                    log.error('商品图片上传失败', err);
                    reject(err);
                }
                resolve();
            });
        }).then(() => {
            //修改商品主图字段
            if (productId && productId !== 'undefined') {
                proCore.find({id: productId}).then(r => {
                    r = r || [];
                    if (r.length > 0) {
                        r = r[0];
                        r.mainImageUrl = url;
                        proCore.edit(r);
                    }
                }, ctx);
            }
            //写入商品图片表
            /*proImgCore.add({
             productId: productId || '',
             url
             }, ctx);*/
            return {productId, name: file.name, uid: file.uid, url};
        });
    }).catch(err => {
        log.error('upload product image is err----', err);
        throw err;
    });
}

export function delFile(query) {
    return utils.resolve().then(() => {
        const {url} = query;
        log.info('del file url param:', url);
        const imgDirPath = path.join(appRoot.toString(), config.productImgDir);
        const configProductImg = imgDirPath.substr(0, imgDirPath.lastIndexOf('\\'));
        const delFilePath = String(path.join(configProductImg, url));
        log.info('del file delFilePath param:', delFilePath);

        return new Promise((resolve, reject) => {
            fs.exists(delFilePath, (exist) => {
                if (!exist) {
                    log.error('check file is not exist url:', url);
                    reject('文件不存在');
                } else {
                    fs.unlink(delFilePath, (err) => {
                        if (err) {
                            log.error(err);
                            reject(err);
                        }
                        resolve('删除成功');
                    });
                }
            });
        });
    }).catch(err => {
        log.error('del file is err----', err);
        throw err;
    });
}

export function uploadActivityImg(ctx) {
    return utils.resolve().then(() => {
        const {files: {file}, fields: {activityId} = {}} = ctx.request.body;
        if (!file || !file.size) {
            throw '文件为空!';
        }
        const filepath = file.path;
        const nowStr = moment().format('YYYYMMDDHHmmss');
        const newFilenName = `${nowStr}${utils.randomDigits(4)}_${String(activityId !== 'undefined' ? activityId : '')}_${file.name}`;
        const url = path.join(config.activityImgDir, moment().format('YYYYMMDD'), newFilenName);
        const destFilePath = path.join(appRoot.toString(), url);
        log.info('rename 图片 %s--->%s', filepath, destFilePath);
        return new Promise((resolve, reject) => {
            fsExtra.move(filepath, destFilePath, (err) => {
                if (err) {
                    log.error('活动图片上传失败', err);
                    reject(err);
                }
                resolve();
            });
        }).then(() => {
            return {activityId, name: file.name, uid: file.uid, url};
        });
    }).catch(err => {
        log.error('upload activity image is err----', err);
        throw err;
    });
}

export function delActivityImg(query) {
    return utils.resolve().then(() => {
        const {id, url} = query;
        log.info('del file url param:', url);
        const imgDirPath = path.join(appRoot.toString(), config.activityImgDir);
        const configActivityImg = imgDirPath.substr(0, imgDirPath.lastIndexOf('\\'));
        const delFilePath = String(path.join(configActivityImg, url));
        log.info('del file delFilePath param:', delFilePath);

        return new Promise((resolve, reject) => {
            fs.exists(delFilePath, (exist) => {
                if (!exist) {
                    log.error('check file is not exist url:', url);
                    reject('文件不存在');
                } else {
                    fs.unlink(delFilePath, (err) => {
                        if (err) {
                            log.error(err);
                            reject(err);
                        }
                        //删除活动图片表数据
                        if (id) {
                            db.get('xp_activityimages').forge({id}).drop();
                        }
                        resolve('删除成功');
                    });
                }
            });
        });
    }).catch(err => {
        log.error('del file is err----', err);
        throw err;
    });
}
